package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.adapter.KeepServerAdapter;
import com.longqinuo.mycarservice.adapter.SecondCarAdapter;
import com.longqinuo.mycarservice.entity.KeepServer;
import com.longqinuo.mycarservice.entity.SecondCar;
import com.longqinuo.mycarservice.manager.IManager;
import com.longqinuo.mycarservice.manager.MangerImpl;
import com.longqinuo.mycarservice.utils.SpaceItemDecoration;
import com.longqinuo.mycarservice.view.LruImageCache;


import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MyCollectFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyCollectFragment extends Fragment implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private SecondCarAdapter mCarAdapter;
    private KeepServerAdapter mServerAdapter;
    private List<SecondCar> mCarList;
    private List<KeepServer> mServerList;
    private LinearLayoutManager layoutManager;

    private FragmentManager manager;
    private FragmentTransaction mTransaction;

    private OnFragmentInteractionListener mListener;
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mOption;
    private TabLayout tab_layout_collect;
    private RecyclerView rv_my_collect_list;

    private static RequestQueue queue;
    private static ImageLoader imageLoader;
    private IManager iManager;   //数据库二手车代理管理器
    private IManager iServerManager;   //数据库套餐代理管理器

    public MyCollectFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MyCollectFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MyCollectFragment newInstance(String param1, String param2) {
        MyCollectFragment fragment = new MyCollectFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        init();
    }
    private void init() {  //初始化操作
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue,lruImageCache);

        manager = getActivity().getSupportFragmentManager();
        iManager = new MangerImpl(getActivity(),new SecondCar());  //数据库二手车代理管理器
        iServerManager = new MangerImpl(getActivity(),new KeepServer());//数据库套餐代理管理器
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_collect, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mBack.setOnClickListener(this);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mTitle.setText("我的收藏");
        mOption = (ImageView) view.findViewById(R.id.iv_top_option);
        mOption.setVisibility(View.INVISIBLE);

        tab_layout_collect = (TabLayout) view.findViewById(R.id.tab_layout_collect);
        tab_layout_collect.addTab(tab_layout_collect.newTab().setText("二手车"));
        tab_layout_collect.addTab(tab_layout_collect.newTab().setText("维保套餐"));
        int colorBlue = getResources().getColor(R.color.colorTabFontSelected);
        int colorDefault = getResources().getColor(R.color.colorGrayFont);
        tab_layout_collect.setTabTextColors(colorDefault,colorBlue);
        tab_layout_collect.setSelectedTabIndicatorColor(colorBlue);

        rv_my_collect_list = (RecyclerView) view.findViewById(R.id.rv_my_collect_list);
        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_my_collect_list.setLayoutManager(layoutManager);
        int space = getResources().getDimensionPixelSize(R.dimen.recycler_divede_line);
        rv_my_collect_list.addItemDecoration(new SpaceItemDecoration(space));
        initData();
        rv_my_collect_list.setAdapter(mCarAdapter);
        tab_layout_collect.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {

                    rv_my_collect_list.setAdapter(mCarAdapter);
                } else {
                    rv_my_collect_list.setAdapter(mServerAdapter);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
    private void initData() {
        mCarList = new ArrayList<>();
        Cursor c = iManager.queryAll();
        if (c!=null&&c.getCount()>0) {
            while (c.moveToNext()) {
                int carId = c.getInt(c.getColumnIndex("car_Id"));
                String image = c.getString(c.getColumnIndex("image"));
                String title = c.getString(c.getColumnIndex("title"));
                double km = c.getDouble(c.getColumnIndex("km"));
                String buyDate = c.getString(c.getColumnIndex("buy_date"));
                double price = c.getDouble(c.getColumnIndex("price"));
                String tab = c.getString(c.getColumnIndex("tab"));
                SecondCar car = new SecondCar(image,km,tab,price,buyDate,carId,title);
                mCarList.add(car);
            }
        }

        mCarAdapter = new SecondCarAdapter(mCarList, R.layout.second_car_item_layout,imageLoader);

        mCarAdapter.setOnItemClickListener(new SecondCarAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                mTransaction = manager.beginTransaction();
                mTransaction.add(R.id.ll_main_layout, SecondInfoFragment.newInstance(mCarList.get(position).getId()+"",""), "SecondInfo");
                mTransaction.addToBackStack("SecondInfo");
                mTransaction.commit();
            }
        });

        mServerList = new ArrayList<>();
        Cursor serverC = iServerManager.queryAll();
        if (serverC!=null&&serverC.getCount()>0) {
            while (serverC.moveToNext()) {
                int serverId = serverC.getInt(serverC.getColumnIndex("server_Id"));
                String name = serverC.getString(serverC.getColumnIndex("name"));
                String image = serverC.getString(serverC.getColumnIndex("image"));
                double currentPrice = serverC.getDouble(serverC.getColumnIndex("price"));
                double oldCurrent = serverC.getDouble(serverC.getColumnIndex("originaPrice"));
                int count = serverC.getInt(serverC.getColumnIndex("count"));
                String location = serverC.getString(serverC.getColumnIndex("location"));
                //(String image, String com_location, double price, String name, int count, int id, double originaPrice)
                KeepServer k = new KeepServer(image,location,currentPrice,name,count,serverId,oldCurrent);
                mServerList.add(k);
            }
        }
        mServerAdapter = new KeepServerAdapter(mServerList,R.layout.keep_server_list_item,imageLoader);

        mServerAdapter.setOnItemClickListener(new KeepServerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                mTransaction = manager.beginTransaction();
                mTransaction.replace(R.id.ll_main_layout,MealInfoFragment.newInstance(mServerList.get(position).getId()+"",""),"MeaLInfo");
                mTransaction.addToBackStack("MeaLInfo");
                mTransaction.commit();
            }
        });
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                manager.popBackStack();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
